<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page -->
<route lang="jsonc" type="home">
{
  "layout": "tabbar",
  "style": {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    "navigationStyle": "custom",
    "navigationBarTitleText": "首页"
  }
}
</route>

<script lang="ts" setup>
import type { WorkbenchStatisticsRes } from '@/api/workbench'
import { getWorkbenchPerformance, getWorkbenchStatistics, } from '@/api/workbench'
import { getUserInfo } from '@/api/userInfo'
import { getItemStatusDetail } from '@/pages/order/dataHandler'
import {useGetOrderStatusActions} from '@/pages/order/dataHandler'
import DiaOrderDetail from '@/pages/order/components/DiaOrderDetail.vue'
import PopCompleteUpload from '@/pages/order/components/PopCompleteUpload.vue'
import { useToast } from 'wot-design-uni'
import dayjs from 'dayjs'
import { useGeoStore } from '@/store'

const geoStore = useGeoStore()

const toast = useToast()
defineOptions({
  name: 'Home',
})
const dia_order_detail = ref()
const complete_upload = ref()
const performanceList = ref([])
const statistics = ref<WorkbenchStatisticsRes>({
  pendingCount: null,
  completedCount: null,
  processingCount: null,
  totalCount: null,
  todayOrder: [],
})
const userInfo = ref({
  nickname: '',
  avatar: '',
  rating: '',
  completeOrderCount: '',
  applauseRate: null,
  monthCompleteOrderCount: '',
})
const dayInfo = ref({
  dateFormat: '',
  amOrPm: ''
})
const arrangeMsg = computed(() => {
  const count = statistics.value.todayOrder.length
  return count ? `您有${count}个待处理工单` : '暂无工单处理'
})
const overviewList = computed(() => {
  const { pendingCount, completedCount, processingCount, totalCount }
    = statistics.value
  return [
    {
      title: '待处理',
      icon: 'icon-clock',
      iconColor: 'text-pink-100',
      bgc: 'bg-pink-50',
      value: pendingCount || 0,
    },
    {
      title: '进行中',
      icon: 'icon-doing',
      iconColor: 'text-green-100',
      bgc: 'bg-green-50',
      value: processingCount || 0,
    },
    {
      title: '今日已完成',
      icon: 'icon-finish',
      iconColor: 'text-sky-100',
      bgc: 'bg-sky-50',
      value: completedCount || 0,
    },
    {
      title: '本周总工单',
      icon: 'icon-list',
      iconColor: 'text-orange-100',
      bgc: 'bg-orange-50',
      value: totalCount || 0,
    },
  ]
})
const _getWorkbenchStatistics = async () => {
  const res = await getWorkbenchStatistics()
  if(!res) return
  if (Array.isArray(res.todayOrder)) {
    res.todayOrder.forEach((item) => {
      const { problemPhotoUrl } = item
      item.imgArr = problemPhotoUrl ? problemPhotoUrl.split(',') : []
      getItemStatusDetail(item)
      item.promiseClock = dayjs(item.promisedArrivalTime).format('HH:mm')
    })
  }
  statistics.value = res
}
const _getWorkbenchPerformance = async () => {
  const res = (await getWorkbenchPerformance()) as Array<any>
  performanceList.value = res ?? []
}
const getPageData = ()=>{
  _getWorkbenchStatistics()
  _getWorkbenchPerformance()
}
const lineChartOption = computed(() => {
  const labelArr = performanceList.value.map(item => item.date)
  const dataArr = performanceList.value.map(item => item.completeOrderCount)
  return {
    legend: {
      top: 10,
      left: 'center',
    },
    grid: {
      top: '8%',
      left: '3%',
      right: '4%',
      bottom: '8%',
      containLabel: true,
    },
    tooltip: {
      trigger: 'item',
      textStyle: {
        // #ifdef MP-WEIXIN
        // 临时解决微信小程序 tooltip 文字阴影问题
        textShadowBlur: 1,
        // #endif
      },
    },
    xAxis: {
      type: 'category',
      data: labelArr,
    },
    yAxis: {
      type: 'value',
      interval: 1,
    },
    series: [
      {
        data: dataArr,
        type: 'line',
        smooth: true,
        showSymbol: false,
      },
    ],
  }
})

const statusActions = useGetOrderStatusActions({successFn:()=>{
  getPageData()
  dia_order_detail.value.close()
}})
const handleBtnClick = (item) => {
  const { status } = item
  if (status === 'ASSIGNED') {
    statusActions.handleSetOff(item)
  } else if (status === 'START') {
    statusActions.handleSignIn(item)
  } else if (status === 'ARRIVED') {
    statusActions.handleStartRepair(item)
  } else if (status === 'REPAIRING') {
    complete_upload.value.open(item)
  } else if (status === 'COMPLETED') {
    // complete_upload.value.open(item)
  }
}

async function _getUserInfo() {
  const res = await getUserInfo()
  Object.assign(userInfo.value, res ?? {})
}
const getDayMsg = () => {
  const date = dayjs().format('YYYY年MM月DD日')
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[dayjs().day()]
  const formattedDate = `${date}${weekday}`
  dayInfo.value.dateFormat = formattedDate
  dayInfo.value.amOrPm = dayjs().hour() < 12 ? '上午' : '下午'
}

onShow(async () => {
  getPageData()
  _getUserInfo()
  getDayMsg()
})
</script>

<template>
  <view class="bg-main h-full">
    <scroll-view :scroll-y="true" style="height: 100%" scrollbar="true">
      <view class="px-4 pb-4 pt-2">
        <view class="mb-3">
          <text class="text-base text-slate-700 font-bold">
            {{dayInfo.amOrPm}}好，{{userInfo.nickname}}
          </text>
          <br>
          <text class="text-sm text-gray-500">
            今天是{{dayInfo.dateFormat }}，{{arrangeMsg}}
          </text>
          <br>

          <view class="text-xs text-desc">
            lng: {{geoStore.geoInfo.longitude}} lat: {{geoStore.geoInfo.latitude}}
          </view>
          <view class="text-xs text-desc">
            upTime: {{geoStore.geoInfo.updateTime}}
          </view>
        </view>

        <view class="gridBox">
          <view
            v-for="oItem in overviewList"
            :key="oItem.icon"
            class="gridItem"
            :class="[oItem.bgc]"
          >
            <view class="flex flex-col">
              <text class="text-xs text-gray-600">
                {{ oItem.title }}
              </text>
              <text>{{ oItem.value }}</text>
            </view>
            <i
              class="iconfont text-6xl"
              :class="[oItem.icon, oItem.iconColor]"
            />
          </view>
        </view>
        <view class="mt-4">
          <text class="text-sm font-bold">
            今日日程
          </text>
          <template v-if="statistics.todayOrder.length">
            <view
              v-for="item in statistics.todayOrder"
              :key="item.orderId"
              class="mt-3 flex justify-between rounded bg-white p-3 shadow-sm"
              @click="dia_order_detail.open(item)"
              >
              <view class="flex gap-3">
                <view class="inline-flex self-start pt-2px">
                  <text
                    class="rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-700"
                  >
                    {{item.promiseClock}}
                  </text>
                </view>
                <view class="flex flex-col gap-0.5">
                  <text>{{item.requestTitle}}-{{item.repairCategory}}</text>
                  <text class="text-sub">
                    {{item.stationLocation ?? '&nbsp;'}}
                  </text>
                  <view class="flex gap-1 items-center">
                    <sar-tag
                      :color="item.status_label_bg"
                      :text-color="item.status_label_color"
                    >
                      {{ item.status_label }}
                    </sar-tag>
                    <text class="text-left text-desc text-xs">距目的地{{ item.distance }}公里</text>
                  </view>
                </view>
              </view>
              <view class="self-end">
                <view v-if="item.status_btn_visible" class="flex items-center text-primary" @click.stop="handleBtnClick(item)">
                  <i class="iconfont pt-2px" :class="[item.status_icon]" />
                  <text> {{ item.status_btn_text }} </text>
                </view>
              </view>
            </view>
          </template>
          <JediEmpty image="content" v-else tip="暂无安排" />
        </view>
        <view class="mt-4">
          <text class="text-sm font-bold">
            本月业绩
          </text>
          <view class="mt-3">
            <LineChart v-if="performanceList.length" :option="lineChartOption" />
            <JediEmpty v-else image="content" tip="暂无完成记录" />
          </view>
        </view>
      </view>
    </scroll-view>
    <DiaOrderDetail
      ref="dia_order_detail"
      @refresh="getPageData"
    />
    <PopCompleteUpload
      ref="complete_upload"
      @refresh="getPageData"
    />
  </view>
</template>

<style lang="scss" scoped>
.gridBox {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  .gridItem {
    display: flex;
    box-sizing: border-box;
    align-items: center;
    width: calc(50% - 6px);
    position: relative;
    @apply h-16 rounded shadow shadow-gray-200 p-3;
    .iconfont {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
}
</style>
